<template>
	<view class="subsection-container">
		<view ref="bar" class="subsection-container-bar" :style="[BarStyle]"></view>
		<view
			class="subsection-container-item"
			@click="changeBlock(index)"
			:class="{ active: currentIndex == index }"
			v-for="(item, index) in list"
			:key="index"
		>
			{{ item }}
		</view>
	</view>
</template>

<script>
function sleep() {
	return new Promise((resolve, reject) => {
		setTimeout(() => {
			resolve();
		}, 200);
	});
}
export default {
	props: {
		list: {
			type: Array,
			default: [],
		},
		curNow: {
			type: [String, Number],
			default: 0,
		},
	},
	watch: {
		curNow: {
			handler(newVal, oldVal) {
				this.currentIndex = newVal;
			},
			immediate: true,
			deep: true,
		},
		list: {
			handler(newVal, oldVal) {
				sleep().then((res) => {
					this.GetRect('.subsection-container-item').then((size) => {
						this.itemRect = size;
					});
				});
			},
		},
	},
	data() {
		return {
			itemRect: {},
			currentIndex: 0,
		};
	},
	mounted() {
		sleep().then((res) => {
			this.GetRect('.subsection-container-item').then((size) => {
				this.itemRect = size;
			});
		});
	},
	computed: {
		BarStyle() {
			const style = {};
			style.width = `${this.itemRect.width}px`;
			style.height = `${this.itemRect.height}px`;
			// 通过translateX移动滑块，其移动的距离为索引*item的宽度
			// #ifndef APP-NVUE
			style.transform = `translateX(${this.currentIndex * this.itemRect.width}px)`;
			// #endif
			return style;
		},
	},

	methods: {
		changeBlock(index) {
			this.currentIndex = index;
			this.$emit('change', index);
		},
		GetRect(selector, all) {
			return new Promise((resolve) => {
				uni
					.createSelectorQuery()
					.in(this)
					[all ? 'selectAll' : 'select'](selector)
					.boundingClientRect((rect) => {
						if (all && Array.isArray(rect) && rect.length) {
							resolve(rect);
						}
						if (!all && rect) {
							resolve(rect);
						}
					})
					.exec();
			});
		},
	},
};
</script>

<style lang="scss" scoped>
.subsection-container {
	position: relative;
	display: flex;
	padding: 0 6rpx;
	height: 72rpx !important;
	// width: 697rpx;
	// background: rgba(255, 255, 255, 0.4) !important;
	
	.active {
		font-family: PingFang SC;
		color: #EDD37D;
		font-weight: 700;
		position:relative;
	}
	.active::after{
		content:"";
		position: absolute;
		bottom: -20rpx;
		left: 50%;
		transform: translate(-50%,0);
		border: 20rpx solid #EDD37D;
		border-color: transparent transparent #EDD37D transparent;
	}
	&-item {
		position: relative;
		z-index: 2;
		display: flex;
		font-size: 32rpx;
		margin-right:50rpx;
		height: 59rpx;
		border-radius: 29rpx;
		color: #ffffff;
	}
	.subsection-container-bar {
		transition: 0.3s all;
		position: absolute;
		z-index: 1;
		border-radius: 36rpx !important;
		background:transparent!important;
	}
}
</style>
